package com.example.transactionstudy.service.impl;

import com.example.transactionstudy.entity.TestTrans;
import com.example.transactionstudy.mapper.ITestMapper;
import com.example.transactionstudy.service.ITestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TestService implements ITestService {
    @Autowired
    private ITestMapper testMapper;
    @Transactional
    @Override
    public int addTest(TestTrans test) {
        int i = testMapper.insert(test);
        return i;
    }
    @Transactional
    @Override
    public TestTrans selectTest(long id) {
        TestTrans trans = testMapper.selectById(id);

        try {
            int z=1/0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return trans;
    }

    @Override
    public int deleteTest(long id) {
        return 0;
    }
//    即使该方法后续报错，但只要执行了数据库操作事件，不使用事务都会成功，开启事务@Transactional可回滚
    @Transactional(rollbackFor = ArithmeticException.class) //回滚规则 rollbackfor表示什么异常回滚，norollbackfor表示什么异常不回滚
    @Override
    public int updateTest(long id) {
        TestTrans trans = selectTest(id);
        trans.setAge(18);
        int i = testMapper.updateById(trans);
//        int z =1/0;
        return i;
    }
}
